<?php

namespace app\modules\controllers;
use app\models\Category;
use app\models\Product;

use yii\web\Controller;
use yii;
use yii\data\Pagination;
use crazyfd\qiniu\Qiniu;
/**
 * Default controller for the `admin` module
 */
class ProductController extends Controller
{
	public $layout='layout1';
    /**
     * Renders the index view for the module
     * @return string
     */
	  public function actionList()
    {
		$model=Product::find();
		$count=$model->count();
	 
		$pageSize=Yii::$app->params['pageSize']['product'];
	 
		$pager=new Pagination(['totalCount'=>$count,'pageSize'=>$pageSize]);
		 
		$products=$model->offset($pager->offset)->limit($pager->limit)->all();
	 
        return $this->render('Products',['pager'=>$pager,'products'=>$products]);
    }
    public function actionAdd()
    {
		 
		$model=new Product;
		$cate=new Category;
		$list=$cate->getOptions();
	 
		if(Yii::$app->request->isPost){
			
			$post=Yii::$app->request->post();
			$pics=$this->upload();
			if(!$pics){
				$model->addError('cover','封面不能为空');
			}
			else{
				$post['Product']['cover']=$pics['cover'];
				$post['Product']['image_list']=$pics['image_list'];
			}
		 
		 
			if($pics && $model->add($post)){
			 
			Yii::$app->session->setFlash('info','添加成功');	
			}else{
				Yii::$app->session->setFlash('info','添加失败');
			}
		}
        return $this->render('add',['opts'=>$list,'model'=>$model]);
    }
	private function upload(){
		 
		if($_FILES['Product']['error']['cover']>0){
			return false;
		}
		
		$qiniu=new Qiniu(Product::AK,Product::SK,Product::DOMAIN,Product::BUKET);
		$key=uniqid();
		$qiniu->uploadFile($_FILES['Product']['tmp_name']['cover'],$key);
		$cover=$qiniu->getLink($key);
		$image_list=[];
		
		foreach($_FILES['Product']['tmp_name']['image_list'] as $k=>$file){
			if($_FILES['Product']['error']['image_list'][$k]>0){
				continue;
			}
			$key=uniqid();
			$qiniu->uploadFile($file,$key);
			$image_list[$key]=$qiniu->getLink($key);
		}
		return ['cover'=>$cover,'image_list'=>json_encode($image_list)];
		
	}
    public function actionProducts()
    {
        return $this->render('Products');
    }

      public function actionSend()
    {
        return $this->render('Send');
    }

    
}
